<template>
  <div id="app">
    <div class="game-container">
      <h1>🎲 摇骰子游戏</h1>
      
      <div class="controls">
        <label>骰子数量:</label>
        <select v-model="diceCount" :disabled="rolling">
          <option v-for="n in 6" :key="n" :value="n">{{ n }}</option>
        </select>
        <button @click="rollDice" :disabled="rolling" class="roll-button">
          <span v-if="!rolling">🎯 摇骰子</span>
          <span v-else>🌀 摇动中...</span>
        </button>
      </div>

      <!-- 骰子容器 -->
      <div class="dice-container">
        <div 
          v-for="(dice, index) in diceDisplay" 
          :key="index" 
          class="dice"
          :class="{
            'rolling': rolling,
            'final': showFinal && !rolling
          }"
          :data-value="dice"
        >
          <div class="dice-face">
            <div class="dot" v-for="n in getDiceDots(dice)" :key="n" :class="`pos-${n}`"></div>
          </div>
        </div>
      </div>

      <!-- 结果显示 -->
      <div v-if="currentRoll.length > 0 && !rolling" class="result">
        <h3>🎊 结果: {{ currentRoll.join(' + ') }} = {{ total }}</h3>
        <p class="result-time">{{ formatTime(resultTimestamp) }}</p>
      </div>

      <!-- 历史记录 -->
      <div class="history">
        <h3>📜 历史记录</h3>
        <div class="history-list">
          <div 
            v-for="(record, index) in history" 
            :key="index" 
            class="history-item"
          >
            <span class="history-time">{{ formatHistory(record).time }}</span>
            <span class="history-result">{{ formatHistory(record).result }}</span>
          </div>
          <div v-if="history.length === 0" class="no-history">
            暂无记录，开始摇骰子吧！
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

const API_BASE = process.env.NODE_ENV === 'development' 
  ? 'http://localhost:8083/api/dice' 
  : '/api/dice';

export default {
  name: 'App',
  data() {
    return {
      diceCount: 1,
      currentRoll: [],
      diceDisplay: [], // 用于显示动画的骰子值
      total: 0,
      rolling: false,
      showFinal: false,
      history: [],
      resultTimestamp: null
    };
  },
  methods: {
    async rollDice() {
      this.rolling = true;
      this.showFinal = false;
      this.currentRoll = [];
      this.diceDisplay = Array(this.diceCount).fill(0);
      
      // 摇动动画 - 快速变化骰子值
      const rollDuration = 2000; // 摇动2秒
      const startTime = Date.now();
      
      const animateRoll = () => {
        if (Date.now() - startTime < rollDuration) {
          // 随机显示骰子值制造动画效果
          this.diceDisplay = this.diceDisplay.map(() => 
            Math.floor(Math.random() * 6) + 1
          );
          requestAnimationFrame(animateRoll);
        } else {
          // 动画结束，获取真实结果
          this.getRealResult();
        }
      };
      
      animateRoll();
    },
    
    async getRealResult() {
      try {
        const response = await axios.post(`${API_BASE}/roll?count=${this.diceCount}`);
        if (response.data.success) {
          this.currentRoll = response.data.dice;
          this.diceDisplay = [...response.data.dice];
          this.total = response.data.total;
          this.resultTimestamp = response.data.timestamp;
          this.showFinal = true;
          await this.loadHistory();
        }
      } catch (error) {
        console.error('摇骰子失败:', error);
        alert('摇骰子失败，请检查网络连接');
      } finally {
        this.rolling = false;
      }
    },
    
    async loadHistory() {
      try {
        const response = await axios.get(`${API_BASE}/history`);
        this.history = response.data.history || [];
      } catch (error) {
        console.error('加载历史记录失败:', error);
      }
    },
    
    formatHistory(record) {
      if (!record) return { time: '', result: '' };
      const parts = record.split(':');
      if (parts.length >= 2) {
        const timestamp = new Date(parseInt(parts[0]));
        const result = parts[1];
        const dice = parts[2] || '';
        return {
          time: timestamp.toLocaleTimeString(),
          result: `点数: ${result} ${dice}`
        };
      }
      return { time: '', result: record };
    },
    
    formatTime(timestamp) {
      if (!timestamp) return '';
      return new Date(timestamp).toLocaleString();
    },
    
    getDiceDots(value) {
      // 返回骰子点数对应的位置
      const dotConfig = {
        1: [5],
        2: [2, 8],
        3: [1, 5, 9],
        4: [1, 3, 7, 9],
        5: [1, 3, 5, 7, 9],
        6: [1, 2, 3, 4, 5, 6]
      };
      return dotConfig[value] || [];
    }
  },
  
  mounted() {
    this.loadHistory();
    // 初始化显示
    this.diceDisplay = Array(this.diceCount).fill(1);
  }
};
</script>

<style scoped>
.game-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  text-align: center;
  color: white;
  min-height: 100vh;
}

.controls {
  margin: 30px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.controls label {
  font-size: 18px;
  font-weight: bold;
}

.controls select {
  padding: 12px 20px;
  font-size: 16px;
  border: none;
  border-radius: 10px;
  background: rgba(255, 255, 255, 0.9);
  cursor: pointer;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}

.roll-button {
  padding: 15px 30px;
  font-size: 18px;
  font-weight: bold;
  border: none;
  border-radius: 50px;
  background: linear-gradient(45deg, #ff6b6b, #ff8e53);
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 6px 20px rgba(255, 107, 107, 0.4);
}

.roll-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(255, 107, 107, 0.6);
}

.roll-button:disabled {
  background: linear-gradient(45deg, #cccccc, #aaaaaa);
  cursor: not-allowed;
  transform: none;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.dice-container {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 25px;
  margin: 40px 0;
  min-height: 120px;
}

.dice {
  width: 80px;
  height: 80px;
  background: linear-gradient(145deg, #ffffff, #f0f0f0);
  border-radius: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-weight: bold;
  color: #333;
  box-shadow: 
    0 8px 25px rgba(0, 0, 0, 0.3),
    inset 0 -4px 8px rgba(0, 0, 0, 0.1),
    inset 0 4px 8px rgba(255, 255, 255, 0.8);
  position: relative;
  overflow: hidden;
}

.dice-face {
  position: relative;
  width: 100%;
  height: 100%;
}

.dot {
  position: absolute;
  width: 12px;
  height: 12px;
  background: #333;
  border-radius: 50%;
  transform: translate(-50%, -50%);
}

/* 骰子点数位置 */
.pos-1 { top: 20%; left: 20%; }
.pos-2 { top: 20%; left: 50%; }
.pos-3 { top: 20%; left: 80%; }
.pos-4 { top: 50%; left: 20%; }
.pos-5 { top: 50%; left: 50%; }
.pos-6 { top: 50%; left: 80%; }
.pos-7 { top: 80%; left: 20%; }
.pos-8 { top: 80%; left: 50%; }
.pos-9 { top: 80%; left: 80%; }

/* 摇动动画 */
.dice.rolling {
  animation: rollDice 0.8s ease-in-out infinite;
}

.dice.final {
  animation: finalBounce 0.6s ease-out;
}

@keyframes rollDice {
  0% { transform: rotate(0deg) scale(1); }
  25% { transform: rotate(90deg) scale(1.1); }
  50% { transform: rotate(180deg) scale(1.2); }
  75% { transform: rotate(270deg) scale(1.1); }
  100% { transform: rotate(360deg) scale(1); }
}

@keyframes finalBounce {
  0% { transform: scale(1.5); }
  50% { transform: scale(0.9); }
  100% { transform: scale(1); }
}

.result {
  margin: 30px 0;
  padding: 20px;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 15px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.result h3 {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: #ffeb3b;
}

.result-time {
  margin: 0;
  font-size: 14px;
  opacity: 0.8;
}

.history {
  margin-top: 40px;
  text-align: left;
}

.history h3 {
  text-align: center;
  margin-bottom: 20px;
  font-size: 22px;
}

.history-list {
  max-height: 300px;
  overflow-y: auto;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 10px;
  padding: 15px;
}

.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  margin: 8px 0;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  transition: background 0.3s ease;
}

.history-item:hover {
  background: rgba(255, 255, 255, 0.2);
}

.history-time {
  font-size: 14px;
  opacity: 0.8;
}

.history-result {
  font-weight: bold;
  color: #4fc3f7;
}

.no-history {
  text-align: center;
  padding: 30px;
  opacity: 0.7;
  font-style: italic;
}

/* 响应式设计 */
@media (max-width: 600px) {
  .game-container {
    padding: 15px;
  }
  
  .dice {
    width: 60px;
    height: 60px;
  }
  
  .controls {
    flex-direction: column;
  }
}
</style>